package DiyPageService

import (
	"context"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func SetActivated(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	var oldModel *entity.DiyPage
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "diy_page").Where("id", req.Id).Struct(&oldModel)
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		// 批量设置当前 page_type 的数据未 未激活
		_, err = tx.Model("diy_page").Unscoped().Where("page_type", oldModel.PageType).Update(g.Map{
			"is_activated": 0,
		})
		if err != nil {
			return err
		}

		_, err = tx.Model("diy_page").Unscoped().Where("id", oldModel.Id).Update(g.Map{
			"is_activated": 1,
		})
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return response.SuccessByRequestMessage(nil, "成功")
}
